﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WeiXinEnterprise.SDK
{
    public interface IVerifyAttribute
    {
        bool Verify(Type type, object obj, out string message);
    }



    public class IsNotNullAttribute : Attribute, IVerifyAttribute
    {
        bool IsNotNull { get; set; }

        string Message { get; set; }

        public IsNotNullAttribute()
        {
            IsNotNull = true;
            Message = "不能为空";
        }

        public IsNotNullAttribute(bool isNotNull)
        {
            IsNotNull = isNotNull;
            Message = "不能为空";
        }
        public IsNotNullAttribute(bool isNull, string message)
        {
            IsNotNull = isNull;
            Message = message;
        }

        public bool Verify(Type type, object obj, out string message)
        {
            message = "";

            if (IsNotNull == false)
            {
                return true;
            }

            if (obj == null)
            {
                message = Message;
                return false;
            }

            if (obj is IList)
            {

                if ((obj as IList).Count <= 0)
                {
                    message = Message;
                    return false;
                }
            }

            return true;
        }
    }




    public class LengthAttribute : Attribute, IVerifyAttribute
    {
        int MinLength { get; set; }

        int MaxLength { get; set; }

        string Message { get; set; }

        public LengthAttribute(int minLength, int maxLength)
        {
            MinLength = minLength;
            MaxLength = maxLength;
            Message = string.Format("长度应在{0}到{1}之间", minLength, maxLength);
        }
        public LengthAttribute(int minLength, int maxLength, string message)
        {
            MinLength = minLength;
            MaxLength = maxLength;
            Message = string.Format(message, minLength, maxLength);
        }

        public bool Verify(Type type, object obj, out string message)
        {
            message = "";

            if (type == typeof(string) && obj != null)
            {
                if ((obj as string).Length > MaxLength || (obj as string).Length < MinLength)
                {
                    message = Message;
                    return false;
                }
            }
            else if(type == typeof(string[]) && obj != null)
            {
                string[] arrary = obj as string[];
                if(arrary.Length > MaxLength || arrary.Length < MinLength)
                {
                    message = Message;
                    return false;
                }
            }

            return true;
        }
    }
}
